﻿using UnityEngine;
using System.Collections;

public class OnTriggerEnter : MonoBehaviour {

	public GameObject player;
	private PlayerSaving playerSaving;

    void Awake()
    {
        //This is set so that LoadLevel on client doesn't destroy player in Server
        DontDestroyOnLoad(gameObject);
    }

    void Start()
    {
        if (!networkView.isMine)
        {
            enabled = false;
        }
		GameObject savingObject = GameObject.Find("PlayerSaving");
        if (savingObject == null)
            return;
		playerSaving = savingObject.GetComponent<PlayerSaving>();

		Debug.Log("positionSaved is " + playerSaving.isSavePositionSaved);
		if (playerSaving.isSavePositionSaved) {
			gameObject.transform.position = playerSaving.savePosition;
		}
	}
	void OnTriggerEnter2D(Collider2D coll){
        Debug.Log("OnTriggerEnter2D");
        if (!networkView.isMine)
        {
            return;
        }
		if (coll.tag == "PlatForm"){
			Physics2D.IgnoreCollision(coll, gameObject.GetComponent<PolygonCollider2D>());
		}
		if (coll.tag == "Spike")
		{
			Debug.Log ("Meet Spike, Die");
            Vector3 vec = gameObject.transform.position;
            networkView.RPC("DeadAnimation", RPCMode.All, vec.x, vec.y, vec.z);
			DestroyAndCreate();
		}

	}
	void OnTriggerExit2D(Collider2D coll){
		
		if (coll.tag == "PlatForm"){
			Physics2D.IgnoreCollision(coll, gameObject.GetComponent<PolygonCollider2D>(),false);
		}
	}
	void DestroyAndCreate()
	{
		Debug.Log("DestroyAndCreate");
        Network.RemoveRPCs(networkView.viewID);
        Network.Destroy(gameObject);
        // destroy the pointer
        // Destroy(GameObject.FindGameObjectsWithTag("Pointer")[0]);
	}

    [RPC]
    public void DeadAnimation(float x, float y, float z)
    {
        GameObject.Instantiate(Resources.Load("dead_body"), new Vector3(x, y, z), Quaternion.identity);
    }

}
